package org.swift.mashup.engine.deployment;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

public class MashupDependents {
	private String name;
	private Map<Long,Set<String>> mapMyFiledateToDependents = new HashMap<Long, Set<String>>();

	public MashupDependents(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setDependent(long myFiledate, String dependent) {
		if ( dependent != null ) {
			removeDependent(dependent);
			Set<String> dependents = getDependents(myFiledate, true);
			dependents.add(dependent);
		}
	}

	public Set<String> getDependents(long myFiledate) {
		return getDependents(myFiledate, false);
	}

	public Set<String> getDependents(long myFiledate, boolean createIfMissing) {
		Set<String> dependents = mapMyFiledateToDependents.get(myFiledate);

		if ( dependents == null && createIfMissing ) {
			dependents = new LinkedHashSet<String>();
			mapMyFiledateToDependents.put(myFiledate, dependents);
		}

		return dependents;
	}

	public void removeDependent(String dependent) {
		if ( dependent != null ) {
			for ( Set<String> depSet : mapMyFiledateToDependents.values() ) {
				depSet.remove(dependent);
			}
		}
	}

	public Set<String> getOutOfDateDependents(long date) {
		Set<String> outOfDateDeps = new LinkedHashSet<String>();

		for ( Map.Entry<Long,Set<String>> entry : mapMyFiledateToDependents.entrySet() ) {
			if ( entry.getKey() < date ) {
				outOfDateDeps.addAll( entry.getValue() );
			}
		}

		return outOfDateDeps;
	}
}
